#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
微信公众号发布管理工具
支持发布草稿、查询发布状态等功能
"""

import requests
import json
import os
from typing import Optional, Dict, Any
from wechat_token import WeChatTokenManager

class WeChatPublishManager:
    """
    微信公众号发布管理类
    """
    
    def __init__(self, token_manager: WeChatTokenManager):
        """
        初始化
        :param token_manager: Token管理器实例
        """
        self.token_manager = token_manager
        self.base_url = "https://api.weixin.qq.com/cgi-bin/freepublish"
    
    def publish_draft(self, media_id: str) -> Dict[str, Any]:
        """
        发布草稿
        :param media_id: 要发布的草稿的media_id
        :return: 发布结果
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/submit"
        params = {'access_token': access_token}
        
        data = {'media_id': media_id}
        
        try:
            print(f"🚀 正在发布草稿: {media_id}")
            
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                error_messages = {
                    48001: "API功能未授权，请确认公众号已获得该接口权限",
                    53503: "该草稿未通过发布检查，请检查草稿信息",
                    53504: "需前往公众平台官网使用草稿",
                    53505: "请手动保存成功后再发表"
                }
                error_msg = error_messages.get(result['errcode'], result.get('errmsg', '未知错误'))
                raise Exception(f"发布草稿失败: {result['errcode']} - {error_msg}")
            
            print(f"✅ 发布任务提交成功!")
            print(f"📋 发布任务ID: {result.get('publish_id')}")
            print(f"📄 消息数据ID: {result.get('msg_data_id')}")
            print(f"⚠️  注意: 发布任务已提交，实际发布完成需要一定时间")
            
            return result
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def get_publish_status(self, publish_id: str) -> Dict[str, Any]:
        """
        查询发布状态
        :param publish_id: 发布任务ID
        :return: 发布状态信息
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/get"
        params = {'access_token': access_token}
        
        data = {'publish_id': publish_id}
        
        try:
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"查询发布状态失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            # 解析发布状态
            status_messages = {
                0: "发布成功",
                1: "发布中",
                2: "原创失败", 
                3: "常规失败",
                4: "平台审核不通过",
                5: "成功后用户删除所有文章",
                6: "成功后系统封禁所有文章"
            }
            
            publish_status = result.get('publish_status', -1)
            status_text = status_messages.get(publish_status, "未知状态")
            
            print(f"📊 发布状态: {status_text} ({publish_status})")
            
            if publish_status == 0:  # 发布成功
                if 'article_detail' in result:
                    article_detail = result['article_detail']
                    print(f"📰 文章数量: {article_detail.get('count', 0)}")
                    for item in article_detail.get('item', []):
                        print(f"  文章 {item.get('idx')}: {item.get('article_url')}")
            elif publish_status in [2, 4]:  # 审核失败
                fail_idx_list = result.get('fail_idx', [])
                if fail_idx_list:
                    print(f"❌ 失败的文章编号: {fail_idx_list}")
            
            return result
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def get_published_list(self, offset: int = 0, count: int = 20, no_content: int = 1) -> Dict[str, Any]:
        """
        获取已发布的图文消息列表
        :param offset: 从全部已发布的图文消息中的该偏移位置开始返回
        :param count: 返回图文消息的数量，取值在1到20之间
        :param no_content: 1表示不返回content字段，0表示返回
        :return: 已发布图文消息列表
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/batchget"
        params = {'access_token': access_token}
        
        data = {
            'offset': offset,
            'count': count,
            'no_content': no_content
        }
        
        try:
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"获取已发布消息列表失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            return result
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def delete_published_article(self, article_id: str, index: int = 0) -> bool:
        """
        删除已发布的图文消息
        :param article_id: 成功发布时返回的 article_id
        :param index: 要删除的文章在图文消息中的位置，第一篇编号为0
        :return: 删除是否成功
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/delete"
        params = {'access_token': access_token}
        
        data = {
            'article_id': article_id,
            'index': index
        }
        
        try:
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"删除已发布文章失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            print(f"✅ 文章删除成功: {article_id}")
            return True
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")


def publish_tepian_draft():
    """发布tepian草稿"""
    from config import WECHAT_CONFIG
    
    print("=== 发布tepian草稿 ===")
    
    # 检查配置
    if WECHAT_CONFIG['APP_ID'] == 'your_app_id_here':
        print("❌ 请先在config.py中配置您的APP_ID和APP_SECRET")
        return
    
    # 读取草稿结果
    draft_result_file = 'tepian_draft_result.json'
    if not os.path.exists(draft_result_file):
        print(f"❌ 找不到草稿结果文件: {draft_result_file}")
        print("请先运行: python upload_material_example.py draft")
        return
    
    try:
        with open(draft_result_file, 'r', encoding='utf-8') as f:
            draft_result = json.load(f)
        
        draft_media_id = draft_result.get('media_id')
        if not draft_media_id:
            print("❌ 无法获取草稿Media ID")
            return
        
        print(f"📋 使用草稿Media ID: {draft_media_id}")
        
        # 创建token管理器和发布管理器
        token_manager = WeChatTokenManager(
            WECHAT_CONFIG['APP_ID'], 
            WECHAT_CONFIG['APP_SECRET']
        )
        publish_manager = WeChatPublishManager(token_manager)
        
        # 发布草稿
        result = publish_manager.publish_draft(draft_media_id)
        
        print(f"✅ 发布任务提交成功!")
        print(f"📋 发布任务ID: {result.get('publish_id')}")
        
        # 保存发布结果
        with open('tepian_publish_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"💾 发布结果已保存到: tepian_publish_result.json")
        
        print(f"\n💡 提示:")
        print(f"- 发布任务已提交，实际发布完成需要一定时间")
        print(f"- 可以使用发布任务ID查询发布状态")
        print(f"- 发布完成后会收到事件推送通知")
        
        return result
        
    except Exception as e:
        print(f"❌ 发布草稿失败: {e}")


def example():
    """
    使用示例
    """
    from config import WECHAT_CONFIG
    
    print("=== 微信公众号发布管理示例 ===")
    
    # 检查配置
    if WECHAT_CONFIG['APP_ID'] == 'your_app_id_here':
        print("⚠️  请先在config.py中配置您的APP_ID和APP_SECRET")
        return
    
    # 创建token管理器和发布管理器
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    publish_manager = WeChatPublishManager(token_manager)
    
    try:
        print("\n1. 获取已发布消息列表...")
        published_list = publish_manager.get_published_list(0, 5, 1)
        total_count = published_list.get('total_count', 0)
        items = published_list.get('item', [])
        
        print(f"📊 已发布消息总数: {total_count}")
        print(f"📝 当前显示: {len(items)} 条消息")
        
        for i, item in enumerate(items):
            print(f"\n消息 {i+1}:")
            print(f"  📋 Article ID: {item.get('article_id')}")
            print(f"  🕒 更新时间: {item.get('update_time')}")
            
            if item.get('content') and item['content'].get('news_item'):
                news_item = item['content']['news_item'][0]
                print(f"  📰 标题: {news_item.get('title', '无标题')}")
                print(f"  🔗 链接: {news_item.get('url', '无链接')}")
        
        print("\n✅ 示例运行完成！")
        
    except Exception as e:
        print(f"❌ 运行失败: {e}")


if __name__ == '__main__':
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == 'tepian':
        publish_tepian_draft()
    else:
        example()
